<?php
/*@文章模块
 *@author wangjian
 *@time 2013-10-20 
 */
if (! defined('BASEPATH')) {
	exit('Access Denied');
}
define("__PATH_ROOT__", str_replace("\\","/",FCPATH));
class Index extends MY_Controller{
	private $username ;//当前登录的用户
	private $ip ; //登录的ip地址
//	private $dir = './data/tree'; //生成的xml文件路径
	private $table_ ; //表的前缀
	private $type_id = 1 ;  //定义文章的类别是分类是1
	private $type_path = "./data/tree" ;
	private $tags_cache_path = "./data/tags_cache";//标签缓存路径
	private $cache_category_file = '' ;//缓存文件名字(分类)
	private $make_html_path = '' ;
	function Index(){
		parent::__construct();
		$this->load->library('admin_common');//加载admin的公用方法
		$this->load->library('archive_common');//加载文章的公用方法
		$this->load->model('admin/archive/M_archive');
		date_default_timezone_set('Asia/Shanghai');
		$this->load->model('admin/M_log');//加载日志模型
		$this->username = $this->get_login_name(); //得到登录的用户名
		$this->ip = $this->admin_common->get_client_ip();
		$this->table_ = $this->admin_common->table_pre('real_data');
		$this->cache_category_file = $this->type_path."/tree_".$this->type_id.".txt" ;
		$this->make_html_path = __PATH_ROOT__."/data/archive" ;
	}
	//文章列表
	function archive_list(){
		$data_  = $_REQUEST ;
		$action = 'show';
		$action_array = array('show','ajax_data');
		$action = (isset($data_['action'])&&in_array($action,$action_array))?$data_['action']:'show';
		
		$category_data = array();
		$category_data = $this->archive_common->get_cateory_data($this->cache_category_file) ;
		$data = array(
			'column'=>$category_data
		);
		if($action == 'show'){
			$this->load->view('admin/archive/views_archive_list',$data);
		}elseif($action == 'ajax_data'){
			$this->ajax_get_data();
			die();
		}
		
	}
	//获取文章列表数据，返回json数据
	private function ajax_get_data(){
	
		$post_data = $this->input->post(NULL,true) ;
		$where = ' where 1=1';
		if(isset($post_data['typeid']) && $post_data['typeid'] != ""){
			$where.=' AND `typeid`='.intval($post_data['typeid']);
		}
		
		if(isset($post_data['title']) && $post_data['title'] != ""){
			$title = str_replace("'", "''", strip_tags(htmlspecialchars($post_data['title'])));  //题目
			$where.=" AND `title` like '%{$title}%'";
		}
		if(isset($post_data['id']) && intval($post_data['id']) != "" && intval($post_data['id']) >0){
			$id = intval($post_data['id']);
			$where.=" AND `id` = '{$id}'";
		}
		if(!isset($post_data['page'])){
			$page  =1 ;
		}else{
			$page = intval($post_data['page']);
		}
	
		$sql_count = "SELECT * FROM {$this->table_}extra_archive ".$where;
		
		$total = $this->M_archive->query_count($sql_count);
		$per_page = 20;//每一页显示的数量
		$page_string = $this->page_string($total, $per_page, $page);
		$limit = ($page-1)*$per_page;
		$sql = "SELECT * FROM {$this->table_}extra_archive $where  ORDER BY id DESC LIMIT ".$limit.",".$per_page;
		$res = $this->M_archive->querylist($sql);
		if($res){
			foreach($res as $res_k=>$res_v){
				$res[$res_k]['typeid'] = htmlspecialchars_decode($this->archive_common->get_category_name($res_v['typeid'],$this->cache_category_file));
				$res[$res_k]['status'] = ($res_v['status'] == 1)?'正常':'<font color="red">失效</font>';
				$res[$res_k]['title'] = "<font color='{$res_v['color']}'>".$res_v['title']."</font>";
			}
			
		}
		$data['result'] = $res ;
		$data['page_string'] = $page_string ;	
		
		echo $this->admin_common->result_to_towf_new($data,'','',null);
	}
	//

	//文章添加模块
	function archive_add(){
		$data_ = $_REQUEST ;
		$action = 'show' ; //定义action
		$action_array = array('show','add','tags','tagsadd','tagslist','del_tag','edit_tag','cache_tags','open_tags_list') ;	
		$action = (isset($data_['action']) && in_array($data_['action'],$action_array))?$data_['action']:'show' ;	
		
		if($action == 'show'){
			$this->load->helper(array('form', 'url'));
			$this->show_add_page() ;//显示添加页面
		}elseif($action == 'open_tags_list'){
			//打开关键词
			$this->open_tags_list();
		}elseif($action == 'add'){
			//添加处理
			$this->load->helper(array('form', 'url'));
			$this->add();
			exit();
		}elseif($action == 'tags'){//显示关键词添加页面
			$this->tags() ;
		}elseif($action == 'tagsadd'){
			$this->tags_add_do();
		}elseif($action == 'tagslist'){
			$this->tagslist();//关键词列表
		}elseif($action == 'del_tag'){
			//删除关键词
			$this->del_tag();
		}elseif($action == 'edit_tag'){
			//修改关键词
			$this->edit_tag();
		}elseif($action == 'cache_tags'){
			//关键词缓存生成
			$this->cache_tags();
		}
		
		
	}
	//添加页面
	private function show_add_page(){
			//从缓存文件里面读取分类
			
			$str_array = $this->archive_common->get_cateory_data($this->cache_category_file) ;
			$data = array(
				'column'=>$str_array
			) ;
			$this->load->view('admin/archive/views_archive_add',$data);
	}
	
	
	
	//显示打开的关键词页面_
	private function open_tags_list(){
		//从缓存文件里面读取关键词
		$array_data = array();
		if(file_exists($this->tags_cache_path."/tags_cache_inc.txt")){
			$data = file_get_contents($this->tags_cache_path."/tags_cache_inc.txt");
			$list =  unserialize($data);
			
		}else{
			$list = '' ;
		}
		$array_data= array(
			'list'=>$list 
		);
		$this->load->view('admin/archive/views_archive_open_tags_list',$array_data);
	}
	
	//添加处理
	private function add(){
		$data_ = $_POST ;
		$title = $this->admin_common->do_addslashes(strip_tags(htmlspecialchars($data_['title'])));  //题目
		$color = $this->admin_common->do_addslashes(strip_tags(htmlspecialchars($data_['color']))); //颜色
		$keyword = $this->admin_common->do_addslashes(strip_tags(htmlspecialchars($data_['keyword']))); //关键词
		$click = intval($data_['click']) ; //点击量
		$status = intval($data_['status']);  //状态 1开启  0 关闭
		$publish_time = $data_['publish_time']; // 发布时间
		$typeid  = intval($data_['typeid']) ;//文章栏目id		
		$content =htmlspecialchars($data_['content']); //内容
	
		$data_archive_insert = array(
			'typeid'=>$typeid,
			'click'=>$click,
			'title'=>$title,
			'status'=>$status,
			'publish_time'=>$publish_time,
			'username'=>$this->username,
			'keywords'=>$keyword,
			'color'=>$color
		) ;
		
		$pic_data = array() ;
		$upload_file_name = '' ;
		if(isset($_FILES['litpic']) && $_FILES['litpic']['name'] != ''){
		  $config['upload_path'] = __PATH_ROOT__.'/uploadfiles/archives';
		  $config['allowed_types'] = 'gif|jpg|png';
		  $config['max_size'] = '2048';
		  $config['file_name'] = "archive_".time();
		 // $config['max_width']  = '1024';
		 // $config['max_height']  = '768';
		  //$field_name = "litpic";
		 $this->load->library('upload', $config);	
			if ( ! $this->upload->do_upload("litpic")){
				$error = array('error' => $this->upload->display_errors());
				showmessage($this->upload->display_errors(),'admin/archive/index/archive_add',3,0) ;
				die();
				
			 }else{
				$pic_data = $this->upload->data();
			 }
		}	
		$insert_array = $this->M_archive->insert_one($data_archive_insert,$this->table_."extra_archive");
		if($insert_array['affect_num'] > 0){
			//
			$this->M_log->insert($insert_array['sql'],'archive_add',$this->username,$this->ip,1,"添加标题是:{$title}成功"); //插入日志记录
			$sql_body_array= array(
				'aid'=>$insert_array['insert_id'],
				'typeid'=>$typeid,
				'litpic'=>(isset($pic_data['file_name'])&& $pic_data['file_name'] !="")?$pic_data['file_name']:'',
				'body'=>$content
			) ;
			$body_array = $this->M_archive->insert_one($sql_body_array,$this->table_."extra_archive_body"); //插入内容
			showmessage("添加标题是:{$title}成功",'admin/archive/index/archive_list',3,1) ;
		}else{
			$this->M_log->insert($insert_array['sql'],'archive_add',$this->username,$this->ip,0,"添加标题是:{$title}失败"); //插入日志记录
			showmessage('数据添加错误','admin/archive/index/archive_add',3,0) ;
		}
	
	}
	
	//关键词管理
	private function tags(){
		$action = 'show' ; //定义action
		$action_array = array('show_add','addtags','tags') ;	
		$action = (isset($data_['action']) && in_array($data_['action'],$action_array))?$data_['action']:'show_add' ;
		if($action == 'show_add'){
			$this->load->view('admin/archive/views_archive_tags');
		}elseif($action == 'addtags'){
			//关键词添加处理
			$this->tags_add_do();
		}
		
	}
	//关键词添加处理
	private function tags_add_do(){
		$data_ = $_POST ;
		$tagname = $this->admin_common->do_addslashes(strip_tags(htmlspecialchars($data_['tagname'])));  //关键词
		$data = array(
			'tagname'=>$tagname,
			'addtime'=>date("Y-m-d H:i:s",time()),
			'addperson'=>$this->username,
		) ;
		$code = 0 ;
		$message = '' ;
		$insert_array = $this->M_archive->insert_one($data,$this->table_."extra_archive_tags");
		if($insert_array['affect_num']>0){
			//添加成功
			$code = 1 ;
			$message = '添加成功';
			$this->M_log->insert($insert_array['sql'],'archive_tags_add',$this->username,$this->ip,1,"添加关键词是:{$tagname}成功"); //插入日志记录
			
			echo $this->admin_common->result_to_towf_new('',$code,$message,null);
			die();
		}else{
			//添加失败
			$code = 1 ;
			$message = '添加失败';
			$this->M_log->insert($insert_array['sql'],'archive_tags_add',$this->username,$this->ip,0,"添加关键词是:{$tagname}失败"); //插入日志记录
			echo $this->admin_common->result_to_towf_new('',$code,$message,null);
			die();
		}
	}
	
	//关键词列表
	function tagslist(){
		$post_data = $this->input->post(NULL,true) ;
		$data = array();
		if(!isset($post_data['page'])){
			$page  =1 ;
		}else{
			$page = intval($post_data['page']);
		}	
		$page = ($page == 0)?1:$page ;
		$sql_count = "SELECT * FROM `{$this->table_}extra_archive_tags` ";
		$total = $this->M_archive->query_count($sql_count);
		$per_page = 10;//每一页显示的数量
		$page_string = $this->page_string($total, $per_page, $page);
		$limit = ($page-1)*$per_page;
		$sql = "SELECT * FROM `{$this->table_}extra_archive_tags` order  by id desc LIMIT ".$limit.",".$per_page;
		$res = $this->M_archive->querylist($sql);
		$data['result'] = $res ;
		$data['page_string'] = $page_string ;	
		echo $this->admin_common->result_to_towf_new($data,'','',null);
	}
	//删除关键词
	private function del_tag(){
		$post_data = $this->input->post(NULL,true) ;
		$id = intval($post_data['id']);
		$del = "DELETE FROM `{$this->table_}extra_archive_tags`  WHERE `id` = '{$id}'";
		$num = $this->M_archive->del_data($del);
		if($num>=1){
			echo $this->admin_common->result_to_towf_new('',1,'删除成功',null);
			$this->M_log->insert($del,'archive_tags_del',$this->username,$this->ip,1,"删除id为{$id}记录成功"); //插入日志记录
			die();
		}else{
			echo $this->admin_common->result_to_towf_new('',0,'删除成失败',null);
			$this->M_log->insert($del,'archive_tags_del',$this->username,$this->ip,0,"删除id为{$id}记录失败"); //插入日志记录
			die();		
		}
	}
	//修改关键词
	private function edit_tag(){
		$post_data = $this->input->post(NULL,true) ;
		$id = intval($post_data['id']);
		$tagname = $this->admin_common->do_addslashes(strip_tags(htmlspecialchars($post_data['tagname'])));  //题目
		$edit = "UPDATE `{$this->table_}extra_archive_tags` SET `tagname` = '{$tagname}' WHERE `id` = '{$id}'";
		$num = $this->M_archive->update_data($edit);
		if($num>=1){
			echo $this->admin_common->result_to_towf_new('',1,'修改成功',null);
			$this->M_log->insert($edit,'archive_tags_edit',$this->username,$this->ip,1,"修改id为{$id}记录成功"); //插入日志记录
			die();
		}else{
			echo $this->admin_common->result_to_towf_new('',0,'修改失败',null);
			$this->M_log->insert($edit,'archive_tags_edit',$this->username,$this->ip,0,"修改id为{$id}记录失败"); //插入日志记录
			die();		
		}		
	}
	
	//生成关键词缓存
	private function cache_tags(){
		
		$list = $this->M_archive->querylist("SELECT * FROM `{$this->table_}extra_archive_tags` order by id desc");
		
		if($list){
			if(!file_exists($this->tags_cache_path)){
				@mkdir($this->tags_cache_path);
			}
			if(!is_really_writable("{$this->tags_cache_path}")){
			
				$code = 0 ;
				$message = "对不起目录{$this->tags_cache_path}不可写,请保证有可写的权限" ;
				echo $this->admin_common->result_to_towf_new('',$code,$message,null);
				return ;
			}
			$str = serialize($list);
			file_put_contents("{$this->tags_cache_path}/tags_cache_inc.txt", $str);
			echo $this->admin_common->result_to_towf_new('',1,'生成缓存成功,路径是在'.$this->tags_cache_path."/tags_cache_inc.txt",null);
			$this->M_log->insert("no_make_tagname_cache_sql",'archive_tags_cache',$this->username,$this->ip,1,"生成缓存成功"); //插入日志记录
			die();
		}else{
			echo $this->admin_common->result_to_towf_new('',0,'生成缓存失败',null);
			$this->M_log->insert('no_make_tagname_cache_sql','archive_tags_cache',$this->username,$this->ip,0,"生成关键词缓存失败"); //插入日志记录
			die();	
		}
	}
	/*@function page_string
	 *@分页返回数据
	 *@total 总的数量
	 *@page_num 每一页显示的数量
	 *@page 当前是第几页数据
	 */
	private function page_string($total,$page_num,$page){
		$page_string = '' ;
		$this->load->library('pagination');//加载分页类
		$this->load->library('MY_Pagination');//加载分页类
		$config['total_rows'] = $total;
		$config['use_page_numbers'] =true; // 当前页结束样式
		$config['per_page'] = $page_num; // 每页显示数量，为了能有更好的显示效果，我将该数值设置得较小
		$config['full_tag_open'] = '<div class="pg">'; // 分页开始样式
		$config['full_tag_close'] = '</div>'; // 分页结束样式
		$config['first_link'] = '首页'; // 第一页显示
		$config['last_link'] = '末页'; // 最后一页显示
		$config['next_link'] = '下一页 >'; // 下一页显示
		$config['prev_link'] = '< 上一页'; // 上一页显示
		$config['cur_tag_open'] = ' <a class="current">'; // 当前页开始样式
		$config['cur_tag_close'] = '</a>'; // 当前页结束样式
		$config['uri_segment'] = 6;
		$config['anchor_class']='class="ajax_page" ';
		$this->pagination->cur_page = $page ;
		$this->pagination->initialize($config); // 配置分页
		$page_string =  $this->pagination->create_links(true,'ajax_data');
		return $page_string ;
	}
	
	//文章编辑模块
	function archive_edit(){
		$this->load->helper(array('form', 'url'));
		$data_  = $_REQUEST ;
		$action = 'show';
		$action_array = array('show','doedit');
		$action = (isset($data_['action'])&&in_array($action,$action_array))?$data_['action']:'show';
		if($action == 'show'){
			$id = intval($_GET['id']);
			$sql="SELECT * FROM {$this->table_}extra_archive AS a,{$this->table_}extra_archive_body AS b where a.id = '{$id}' and a.id = b.aid limit 1";
			$row = $this->M_archive->querylist($sql);
			if(empty($row)){
				showmessage('非法访问','admin/archive/index/archive_list',3,0) ;
				exit();
			}
			$str_array = $this->archive_common->get_cateory_data($this->cache_category_file) ;
			$data = array(
					'column'=>$str_array,
					'row'=>$row[0]
			) ;
			
			$this->load->view('admin/archive/views_archive_edit',$data);			
		}elseif($action == 'doedit'){
			$this->do_edit();
		}

	}
	//处理文章编辑
	private function do_edit(){
		$data_ = $_POST ;
		$title = $this->admin_common->do_addslashes(strip_tags(htmlspecialchars($data_['title'])));  //题目
		$color = $this->admin_common->do_addslashes(strip_tags(htmlspecialchars($data_['color']))); //颜色
		$keyword = $this->admin_common->do_addslashes(strip_tags(htmlspecialchars($data_['keyword']))); //关键词
		$click = intval($data_['click']) ; //点击量
		$status = intval($data_['status']);  //状态 1开启  0 关闭
		$publish_time = $data_['publish_time']; // 发布时间
		$typeid  = intval($data_['typeid']) ;//文章栏目id
		$content =htmlspecialchars(str_replace("'", "''", $data_['content'])); //内容
		$picname = $data_['picname'];
		$id = intval($data_['id']);
		
		$pic_data = array() ;
		$upload_file_name = '' ;
		if(isset($_FILES['litpic']) && $_FILES['litpic']['name'] != ''){
		
			$config['upload_path'] = __PATH_ROOT__.'/uploadfiles/archives';
			$config['allowed_types'] = 'gif|jpg|png';
			$config['max_size'] = '2048';
			$config['file_name'] = "archive_".time();
			// $config['max_width']  = '1024';
			// $config['max_height']  = '768';
			//$field_name = "litpic";
			$this->load->library('upload', $config);
			if ( ! $this->upload->do_upload("litpic")){
				$error = array('error' => $this->upload->display_errors());
				showmessage($this->upload->display_errors(),'admin/archive/index/archive_edit?id='.$id,3,0) ;
				die();
		
			}else{
				$pic_data = $this->upload->data();
				if(file_exists(__PATH_ROOT__.'/uploadfiles/archives'."/$picname")){
					@unlink(__PATH_ROOT__.'/uploadfiles/archives'."/$picname") ;
				}
				
			}
		}
		$picname = isset($pic_data['file_name'])&& $pic_data['file_name'] !=""?$pic_data['file_name']:$picname;
		$sql_update = "UPDATE ".$this->table_."extra_archive"." SET typeid = '{$typeid}',`click` = '{$click}',
		`title` = '{$title}',`status` = '{$status}',`publish_time` = '{$publish_time}',
		`username` = '{$this->username}',`keywords` = '{$keyword}',`color` = '{$color}' where id = '{$id}'" ;
		
		$num = $this->M_archive->update_data($sql_update);
		//
		$sql_body_update = "UPDATE " .$this->table_."extra_archive_body SET typeid = '{$typeid}',`litpic` ='{$picname}',`body` = '{$content}' where aid = '{$id}' ";
		$body_array = $this->M_archive->update_data($sql_body_update); //修改内容
		$this->M_log->insert($sql_update,'archive_edit',$this->username,$this->ip,1,"修改标题是:{$title}失败"); //插入日志记录
		showmessage("修改标题是:{$title}成功",'admin/archive/index/archive_list',3,1) ;
	
	}
	
	//文章生成
	function archive_make(){
		set_time_limit(0) ;
		$post_data = $this->input->post(NULL,true) ;
		$post_data = $_REQUEST ;
		$id = $post_data['id'];
		$id_array = explode(",", $id);
		$s_id = '' ;
		if($id_array){
			for($k = 0 ;$k<count($id_array) ;$k++){
				$s_id.=intval($id_array[$k]).",";
			}
			$s_id = rtrim($s_id,",");
		}
		if(empty($s_id)){
			echo $this->admin_common->result_to_towf_new('',0,'参数传递失败',null);
			die();
		}
		$sql_ = "SELECT * FROM ".$this->table_."extra_archive AS a,".$this->table_."extra_archive_body AS b WHERE a.id in ($s_id) and a.id = b.aid" ;
		$list = $this->M_archive->querylist($sql_);
		/* echo "<pre>";
		print_r($list); */
	
		if($list){
			foreach($list as $key=>$val){
				if(!file_exists(__PATH_ROOT__."/data/archive/".$val['typeid'])){//创建缓存文件夹
					$this->archive_common->s_mkdir(__PATH_ROOT__."/data/archive/".$val['typeid']);
				}
				
				$list[$key]['typename'] = $this->get_type_name_by_typeid($val['typeid']) ;
				//$c_ = "var archive_".$val['typeid']."_".$val['id']." = ";
				//$c_.="[{";
				//foreach($val as $v_k=>$v_v){
					//$v_v = base64_encode(iconv("gbk","UTF-8//TRANSLIT",$v_v));
				 	//$c_.="'{$v_k}':'{$v_v}',";
				 	
				 	
			//	}
				//$c_ = rtrim($c_,",");
			//	$c_.=",'typename':'{$this->get_type_name_by_typeid($val['typeid'])}'";
				//$c_.="}];";
				$c_ = serialize($list);
				@file_put_contents(__PATH_ROOT__."/data/archive/".$val['typeid']."/archive_".$val['typeid']."_".$val['id'].".inc.txt", $c_);
			}
			//生成typeid 和typename对应的js文件
			
			
			@file_put_contents(__PATH_ROOT__."/data/archive/type_id_name.inc.txt", serialize($this->get_typeid_typename()));
			echo $this->admin_common->result_to_towf_new('',1,'生成成功',null);
		}
		
	}
	//根据id查找类别名称
	private function get_type_name_by_typeid($id){
		$sql_ = "SELECT tree_name FROM {$this->table_}common_tree WHERE tree_type = {$this->type_id} and tree_id = '{$id}' limit 1 ";
		$list = $this->M_archive->querylist($sql_);
		if(empty($list)){
			return '' ;
		}
		return $list[0]['tree_name'];
	}
	//查找id和typename的对应关系
	private function get_typeid_typename(){
		$sql_ = "SELECT tree_id,tree_name FROM {$this->table_}common_tree WHERE tree_type = {$this->type_id}  ";
		$list = $this->M_archive->querylist($sql_);
		$last = array();
		if($list){
			foreach($list as $k=>$v){
				$last[$v['tree_id']] = $v['tree_name'];
			}
		}
		return $last ;
	}
}
